// 定义中心点和半径
// const center = { latitude: 39.9042, longitude: 116.4074 }; // 替换为火星坐标
// const radius = 1000; // 半径，单位是米

// 生成圆的点集
function generateCirclePoints(center: any, radius: any, numPoints = 1000) {
  const points = [];
  for (let i = 0; i < numPoints; i++) {
    const angle = (i / numPoints) * 2 * Math.PI;
    const x = center.longitude + (radius * Math.cos(angle)) / 111320; // 经度方向上的偏移
    const y = center.latitude + (radius * Math.sin(angle)) / 110540; // 纬度方向上的偏移
    points.push([x, y]);
  }
  return points;
}

// 创建GeoJSON对象
export const useCreateGeoJSONCircle = (center: any, radius: any, numPoints = 1000) => {
  const points = generateCirclePoints(center, radius, numPoints);
  points.push(points[0]); // 闭合多边形

  return {
    type: "Feature",
    geometry: {
      type: "Polygon",
      coordinates: [points]
    },
    properties: {}
  };
}

/** 计算两个坐标的距离，单位米 **/
function Distance(lng1: any, lat1: any, lng2: any, lat2: any) {
  //采用Haversine formula算法，高德地图的js计算代码，比较简洁 https://www.cnblogs.com/ggz19/p/7551088.html
  var d = Math.PI / 180;
  var f = lat1 * d, h = lat2 * d;
  var i = lng2 * d - lng1 * d;
  var e = (1 - Math.cos(h - f) + (1 - Math.cos(i)) * Math.cos(f) * Math.cos(h)) / 2;
  return 2 * 6378137 * Math.asin(Math.sqrt(e));
}

export const useSimpleCircle = (lng: any, lat: any, radius: any, pointCount = 73) => {
  //球面坐标不会算，转换成三角坐标简单点，经度代表值大约：0.01≈1km 0.1≈10km 1≈100km 10≈1000km
  var km = radius / 1000;
  var a = km < 5 ? 0.01 : km < 50 ? 0.1 : km < 500 ? 1 : 10;
  var b = Distance(lng, lat, lng + a, lat);
  var c = Distance(lng, lat, lng, lat + a);
  var rb = radius / b * a;
  var rc = radius / c * a;
  var arr = [];
  var n = 0, step = 360.0 / pointCount, N = 360 - step / 2; //注意浮点数±0.000000001的差异
  for (var i = 0; n < N; i++, n += step) {
    var x = lng + rb * Math.cos(n * Math.PI / 180);
    var y = lat + rc * Math.sin(n * Math.PI / 180);
    arr[i] = [x, y];
  }
  arr.push([arr[0][0], arr[0][1]]); //闭环
  return arr;
};
